package controllers;

import libs.Validation;
import models.Users;
import models.forms.LoginForm;
import play.data.Form;
import play.mvc.Controller;
import play.mvc.Result;
import views.html.index;
import views.html.login;
import business.UserBusiness;

public class Application extends Controller {

	public static Result index() {
		return ok(index.render("Your new application is ready."));
	}

	public static Result login() {
		Form<LoginForm> loginForm = Form.form(LoginForm.class);
		if (Validation.isPost()) {
			Form<LoginForm> filledForm = loginForm.bindFromRequest();
			if (filledForm.hasErrors()) {
				return badRequest(login.render());
			} else {
				LoginForm form = filledForm.get();
				UserBusiness userBusiness = new UserBusiness();
				Users user = userBusiness.login(form);
				if (user != null) {
					System.out.println("1");
					session("userId", String.valueOf(user.getId()));
					session("userName", user.getUsername());
					session("userFullName", user.getFullName());
					return redirect(routes.Application.index());
				} else {
					System.out.println("2");
					filledForm.reject("username", "Login failed! Your username or password is invalid!");
				}
			}
		}
		return ok(login.render());
	}

	public static Result logout() {
		// session().clear();
		return redirect(routes.Application.login());
	}

}
